package models

import (
	"context"
	"strconv"

	"github.com/jinzhu/gorm"
	"go-papers/pkg/lognew"
)

type DataScope struct {
	Uid        int    `json:"uid"`
	NeedVerify bool   `json:"need_verify"`
	UidType    string `json:"uid_type"`
	OrganId    []int  `json:"organId"`
}

func (e *DataScope) GetUserInfo(uid int, uType string) DataScope {
	var doc DataScope
	doc.Uid = uid
	doc.UidType = uType
	var orid []int

	if uType == "2" {
		doc.NeedVerify = true
		// 插叙用户拓展的机构
		var organ Organ
		doc.OrganId = organ.GetOrganIdByUid(uid, false)

	} else if uType == "3" {
		doc.NeedVerify = true

	}
	doc.OrganId = orid
	return doc
}

func (e *DataScope) GetUserInfoByUidStr(uidstr string) DataScope {

	uid, _ := strconv.Atoi(uidstr)
	var sysU SysUser
	uInfo, _ := sysU.GetById(uid)
	uType := uInfo.UserType
	var doc DataScope
	doc.Uid = uid
	doc.UidType = uType
	var orid []int

	if uType == "2" {
		doc.NeedVerify = true

		memId := uInfo.UserMemberId
		// 插叙用户拓展的机构
		var organ Organ
		ll := organ.GetOrganIdByUid(memId, false)
		if len(ll) <= 0 {
			orid = append(orid, 22)
		} else {
			orid = ll
		}

		if orid == nil {
			orid = []int{22}
		}
	} else if uType == "3" {
		doc.NeedVerify = true
		orid = append(orid, uInfo.OrganId)
	}
	doc.OrganId = orid

	if uType != "1" {
		lognew.Info(context.TODO(), "GetUserInfoByUidStr", lognew.Fields{"doc": doc, "uidstr": uidstr, "uInfo": uInfo})
	}
	return doc
}

func HandleOrganCommonTable(table *gorm.DB, source string, uid, msg string) (*gorm.DB, bool) {
	//是否有 organId
	if uid != "" {
		var dd DataScope
		sin := dd.GetUserInfoByUidStr(uid)
		if len(sin.OrganId) > 0 {
			table = table.Where(" `"+source+"`.organ_id in (?)", sin.OrganId)
		}

		// lognew.Info(context.TODO(), "HandleOrganCommonTable--filter", lognew.Fields{"source": source, "msg": msg, "sin": sin})
		return table, sin.NeedVerify
	}
	return table, false
}
